<script setup lang="ts">
import { ref, toRaw } from "vue";

import Searchbox from "@/views/components/searchbox/Searchbox.vue";
import OpLog from "@/views/apply/tankReport/component/opLog.vue";
import { pageSizeOptions } from "@/utils/appCommon/appCommonOptions/app";
import { useRoute } from "vue-router";
import { useUserStore } from "@/store/modules/user";
import { storeToRefs } from "pinia";
import { useI18n } from "vue-i18n";
import { getDeviceGroupOptionsApi } from "@/api/products/deviceGroup";
import { handleTree } from "@/utils/tree";
import { getDeviceOptionsApi } from "@/api/products/device";
import { getProductListApi } from "@/api/products/product";
import { useLogic } from "@/views/system/user/logic/logic";


defineOptions({
  name: "tankReport",
});

const pageSizeOps = ref(pageSizeOptions)
const route = useRoute();
const storeInfo = useUserStore()
const {deptId}= storeToRefs(storeInfo)
const { t } = useI18n();
// 搜索处理 - 增加搜索参数存储
const searchParams = ref({
  deptId: deptId.value,  //初始部门id
  productId: undefined,
  productKey: undefined,
  deviceGroupId: undefined,
  deviceNos:[],
  page:1,
  pageSize:500,
  timeRange: [],
});

const selected = ref(0);

function tabClick({ index }) {
  selected.value = index;
}

let productList = [];
const productOptions = ref([]);
const deviceGroupOptions = ref([]);
const {deptTreeList,getDeptTree}  = useLogic()
const deviceNoOptions = ref([])
const distributeTableOptions = ref([]);

const listComponents = [
  {
    key: "OpLog",
    title: "数据列表",
    component: OpLog
  },
];

const reloadThisPage = async () => {
  await getDeptTree()
  const productOptionsRes = await getProductListApi({
    pageSize:500,
    page:1,
    wheres:{
      openStatus:1,
    },
  })
  if(productOptionsRes.code == 0){
    productList = productOptionsRes.data.list ? productOptionsRes.data.list : [];
    productOptions.value = [
      ...productOptionsRes.data.list.map(option => ({
        val: option.id,
        label: option.name
      }))
    ];
  }
  await reLoadDeviceGroups()
}

const reLoadDeviceGroups = async ()=>{
  const req = new Map;
  if(searchParams.value.deptId){
    req.deptId = searchParams.value.deptId;
  }
  const deviceGroupOptionsRes = await getDeviceGroupOptionsApi(req)
  if(deviceGroupOptionsRes.code == 0){
    deviceGroupOptions.value = handleTree(deviceGroupOptionsRes.data.options);
    console.log(toRaw(deviceGroupOptions.value))
  }
}

const reLoadDevices = async ()=>{
  const req = {
    fieldKey:"deviceNo",
    fieldLabel:"name",
  };
  if(searchParams.value.deptId){
    req.deptId = searchParams.value.deptId;
  }
  if(searchParams.value.productId){
    req.productId = searchParams.value.productId;
  }
  if(searchParams.value.deviceGroupId){
    req.deviceGroupId = searchParams.value.deviceGroupId;
  }
  deviceNoOptions.value = [];
  const deviceOptionsRes = await getDeviceOptionsApi(req)
  if(deviceOptionsRes.code == 0){
    deviceNoOptions.value = deviceOptionsRes.data.options;
  }
}

const searchFields = ref([
  {
    prop: "productId",
    name: t('datacenter.iotdataPage.product'),
    type: "select",
    clearable: false,
    isHidden: false,
    formOptions: productOptions
  },
  {
    prop: "deviceNos",
    name: t('datacenter.iotdataPage.deviceNo'),
    type: "multiSelect",
    clearable: true,
    isHidden: false,
    formOptions: deviceNoOptions
  },
  {
    prop: 'timeRange',
    name: t('datacenter.iotdataPage.timeRange'),
    type: 'datetimeRange',
    clearable: true,
    isHidden: false,
  },
  {
    prop: 'deviceGroupId',
    name: t('datacenter.iotdataPage.deviceGroup'),
    type: 'cascader',
    cascaderOptions: deviceGroupOptions,
    clearable: true,
    isHidden: false,
    ops: {
      valueField: 'id',
      labelField: 'name',
      emitPath: false,
      checkStrictly: true
    }
  },
  {
    prop: 'deptId',
    name: t('datacenter.iotdataPage.dept'),
    type: 'cascader',
    cascaderOptions: deptTreeList,
    clearable: true,
    isHidden: false,
    ops: {
      valueField: 'id',
      labelField: 'name',
      emitPath: false,
      checkStrictly: true
    }
  },
  {
    prop: 'distributeTableId',
    name: t('datacenter.iotdataPage.distributeTable'),
    type: 'select',
    clearable: true,
    isHidden: false,
    formOptions: distributeTableOptions
  },
])

const handleChange = (e: any) => {
  console.log(e)
  if(e.productId != searchParams.value.productId){
    searchParams.value.productId = e.productId
    searchParams.value.deviceNos = []
    searchParams.value.productKey = productList.find(item => item.id === e.productId)?.productKey || '';
    reLoadDevices()
  }
  if(e.deptId != searchParams.value.deptId){
    searchParams.value.deptId = e.deptId
    reLoadDeviceGroups()
    reLoadDevices()
  }
  if(e.deviceGroupId != searchParams.value.deviceGroupId){
    searchParams.value.deviceGroupId = e.deviceGroupId
    reLoadDevices()
  }
}

const total = ref(0)
const iotData = ref([])
const handleSearch = (e:any) => {
  searchParams.value.page = 1
  console.log(e)
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
  searchParams.value.productKey = productList.find(item => item.id === searchParams.value.productId)?.productKey || '';
}

const handleReset = (e:any) => {
  console.log(e)
}

// 分页变化处理
const handleSizeChange = (pageSize: number) => {
  searchParams.value.pageSize = pageSize;
};
const handleCurrentChange = (currentPage: number) => {
  searchParams.value.page = currentPage;
};

</script>

<template>
  <el-card shadow="never">
    <template #header>
      <div class="card-header">
        <Searchbox
          :fields= searchFields
          :initialValues="searchParams"
          :maxVisibleFields=3
          @change="handleChange"
          @search="handleSearch"
          @reset="handleReset"
        />
      </div>
    </template>

    <el-tabs @tab-click="tabClick" >
      <template v-for="(item, index) of listComponents" :key="item.key">
        <el-tab-pane :lazy="true">
          <template #label>
            <span
              v-tippy="{
                maxWidth: 'none',
                content: `${item.title}`
              }"
            >
              {{ item.title }}
            </span>
          </template>
          <keep-alive>
            <component :is="item.component" :key="item.key" v-show="selected == index" />
          </keep-alive>
        </el-tab-pane>
      </template>
    </el-tabs>

  </el-card>
</template>

<style scoped lang="scss">

</style>

